﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Configuration;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


namespace OverNANA
{
    public partial class Form1 : Form
    {
        private bool ZippedFiles;
        private string UpdateURL;
        private string DownLoadDIR;
        
        private DataTable ExceptionList;
        private DataTable dtDownloadList;

        public Form1()
        {
            InitializeComponent();
            ExceptionList = new DataTable("ExceptionList");
            ExceptionList.Columns.Add("Exception");
            ExceptionList.Columns.Add("Message");
            ExceptionList.Columns.Add("URLS");
            ExceptionList.Columns.Add("DateTime", Type.GetType("System.DateTime"));

            dtDownloadList = new DataTable();
            dtDownloadList.Columns.Add("Name");
            dtDownloadList.Columns.Add("URL");

            tsslVersion.Text = "OverNANA V1.2.130222a";
            tsslVersion.ToolTipText = "OverNANA V1.2.130222a";
            ReadSettings();
            tsslState.Text = DownLoadDIR;

            downloadProcess1.downLoadDir = DownLoadDIR;
            downloadProcess1.zippedFiles = ZippedFiles;
            downLoadProcess2.downLoadDir = DownLoadDIR;
            downLoadProcess2.zippedFiles = ZippedFiles;
            downLoadProcess3.downLoadDir = DownLoadDIR;
            downLoadProcess3.zippedFiles = ZippedFiles;
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            dtDownloadList.Rows.Add(new object[] { "", textBox1.Text });
            textBox1.Text = "";
            timer1.Start();
        }


        /// <summary>
        /// 分析全站漫画地址(异步模式)
        /// </summary>
        /// <returns></returns>
        private DataTable AnalysisFullSiteAsync()
        {
            DataTable dtComicList = new DataTable();
            dtComicList.Columns.Add("Name");
            dtComicList.Columns.Add("URL");

            DataTable dtCatalog = new DataTable();
            dtCatalog.Columns.Add("CatalogURL");

            //backgroundWorker1.ReportProgress(0, new ProcessReport("tsslState.Text", "正在获取主页面"));

            string PageContent;
            PageContent = DownLoadCommon.GetHttp("http://www.nanadm.com/", "", "utf-8");

            string CatalogContent;
            //CatalogContent = PageContent.Substring(PageContent.IndexOf("字母检索"));
            //CatalogContent = CatalogContent.Substring(CatalogContent.IndexOf("<div"));
            //CatalogContent = CatalogContent.Substring(0, CatalogContent.IndexOf("</div>"));

            //backgroundWorker1.ReportProgress(0, new ProcessReport("tsslState.Text", "正在分析目录列表"));

            //do
            //{
            //    if (CatalogContent.IndexOf("href=") < 0)
            //        break;
            //    string CatalogEntry = CatalogContent.Substring(CatalogContent.IndexOf("href=") + 6);
            //    CatalogEntry = CatalogEntry.Substring(0, CatalogEntry.IndexOf("</a>"));
            //    if (CatalogEntry.IndexOf("target=") > 0)
            //        CatalogEntry = CatalogEntry.Substring(0, CatalogEntry.IndexOf("target="));
            //    CatalogEntry = CatalogEntry.Replace("'", "");
            //    CatalogEntry = CatalogEntry.Replace("\"", "").Trim();
            //    CatalogEntry = "http://www.nanadm.com" + CatalogEntry;

            //    dtCatalog.Rows.Add(new object[] { CatalogEntry });
            //    CatalogContent = CatalogContent.Substring(CatalogContent.IndexOf("</a>") + 4);
            //} while (true);
            dtCatalog.Rows.Add(new object[] { "http://www.nanadm.com/a/manhuazaixian/zimujiansuo/A/" });
            dtCatalog.Rows.Add(new object[] { "http://www.nanadm.com/a/manhuazaixian/zimujiansuo/B/" });
            dtCatalog.Rows.Add(new object[] { "http://www.nanadm.com/a/manhuazaixian/zimujiansuo/C/" });
            dtCatalog.Rows.Add(new object[] { "http://www.nanadm.com/a/manhuazaixian/zimujiansuo/D/" });
            dtCatalog.Rows.Add(new object[] { "http://www.nanadm.com/a/manhuazaixian/zimujiansuo/E/" });
            dtCatalog.Rows.Add(new object[] { "http://www.nanadm.com/a/manhuazaixian/zimujiansuo/F/" });
            dtCatalog.Rows.Add(new object[] { "http://www.nanadm.com/a/manhuazaixian/zimujiansuo/G/" });
            dtCatalog.Rows.Add(new object[] { "http://www.nanadm.com/a/manhuazaixian/zimujiansuo/H/" });
            dtCatalog.Rows.Add(new object[] { "http://www.nanadm.com/a/manhuazaixian/zimujiansuo/I/" });
            dtCatalog.Rows.Add(new object[] { "http://www.nanadm.com/a/manhuazaixian/zimujiansuo/J/" });
            dtCatalog.Rows.Add(new object[] { "http://www.nanadm.com/a/manhuazaixian/zimujiansuo/K/" });
            dtCatalog.Rows.Add(new object[] { "http://www.nanadm.com/a/manhuazaixian/zimujiansuo/L/" });
            dtCatalog.Rows.Add(new object[] { "http://www.nanadm.com/a/manhuazaixian/zimujiansuo/M/" });
            dtCatalog.Rows.Add(new object[] { "http://www.nanadm.com/a/manhuazaixian/zimujiansuo/N/" });
            dtCatalog.Rows.Add(new object[] { "http://www.nanadm.com/a/manhuazaixian/zimujiansuo/O/" });
            dtCatalog.Rows.Add(new object[] { "http://www.nanadm.com/a/manhuazaixian/zimujiansuo/P/" });
            dtCatalog.Rows.Add(new object[] { "http://www.nanadm.com/a/manhuazaixian/zimujiansuo/Q/" });
            dtCatalog.Rows.Add(new object[] { "http://www.nanadm.com/a/manhuazaixian/zimujiansuo/R/" });
            dtCatalog.Rows.Add(new object[] { "http://www.nanadm.com/a/manhuazaixian/zimujiansuo/S/" });
            dtCatalog.Rows.Add(new object[] { "http://www.nanadm.com/a/manhuazaixian/zimujiansuo/T/" });
            dtCatalog.Rows.Add(new object[] { "http://www.nanadm.com/a/manhuazaixian/zimujiansuo/U/" });
            dtCatalog.Rows.Add(new object[] { "http://www.nanadm.com/a/manhuazaixian/zimujiansuo/V/" });
            dtCatalog.Rows.Add(new object[] { "http://www.nanadm.com/a/manhuazaixian/zimujiansuo/W/" });
            dtCatalog.Rows.Add(new object[] { "http://www.nanadm.com/a/manhuazaixian/zimujiansuo/X/" });
            dtCatalog.Rows.Add(new object[] { "http://www.nanadm.com/a/manhuazaixian/zimujiansuo/Y/" });
            dtCatalog.Rows.Add(new object[] { "http://www.nanadm.com/a/manhuazaixian/zimujiansuo/Z/" });
            dtCatalog.Rows.Add(new object[] { "http://www.nanadm.com/a/manhuazaixian/zimujiansuo/0_9/" });
            
            for (int i = 0; i < dtCatalog.Rows.Count; i++)
            {
                //backgroundWorker1.ReportProgress(0, new ProcessReport("tsslState.Text", "正在整理漫画地址(" + Convert.ToString(i + 1) + "/" + Convert.ToString(dtCatalog.Rows.Count) + ")"));

                PageContent = DownLoadCommon.GetHttp(Convert.ToString(dtCatalog.Rows[i].ItemArray[0]), "", "utf-8");

                PageContent = PageContent.Substring(PageContent.IndexOf("<div class=\"fenliett\">"));
                PageContent = PageContent.Substring(PageContent.IndexOf("<ul"));
                PageContent = PageContent.Substring(0, PageContent.IndexOf("</ul>"));

                do
                {
                    if (PageContent.IndexOf("<li>") < 0)
                        break;
                    string ComicURL, ComicName;

                    string ComicEntry = PageContent.Substring(PageContent.IndexOf("<li>"));
                    ComicEntry = ComicEntry.Substring(0, ComicEntry.IndexOf("</li>"));
                    ComicEntry = ComicEntry.Substring(ComicEntry.LastIndexOf("<a "));
                    ComicEntry = ComicEntry.Substring(0, ComicEntry.IndexOf("</a>"));
                    ComicEntry = ComicEntry.Replace("\"", "'");

                    ComicURL = ComicEntry.Substring(ComicEntry.IndexOf("href=") + 6);
                    ComicURL = ComicURL.Substring(0, ComicURL.IndexOf("'"));
                    ComicURL = "http://www.nanadm.com" + ComicURL;

                    ComicName = ComicEntry.Substring(ComicEntry.IndexOf(">") + 1);
                    ComicName = ComicName.Replace("<p>", "");
                    ComicName = ComicName.Replace("</p>", "");

                    dtComicList.Rows.Add(new object[] { ComicName, ComicURL });
                    PageContent = PageContent.Substring(PageContent.IndexOf("</li>") + 5);

                } while (true);

            }

            return dtComicList;
        }
        
        /// <summary>
        /// 分析漫画更新页面(异步方式)
        /// </summary>
        /// <returns></returns>
        private DataTable AnalysisUpdateAsync()
        {
            //backgroundWorker1.ReportProgress(0, new ProcessReport("tsslState.Text", "正在获取更新信息"));
            DataTable dtBookList = new DataTable();
            dtBookList.Columns.Add("Name");
            dtBookList.Columns.Add("URL");

            string PageHTTP = DownLoadCommon.GetHttp(UpdateURL, "", "utf-8");
            if (PageHTTP.IndexOf("<div class=\"fenliett\">") <= 0)
            {
                //backgroundWorker1.ReportProgress(0, new ProcessReport("tsslState.Text", "更新地址不正确"));
                return dtBookList;
            }
            PageHTTP = PageHTTP.Substring(PageHTTP.IndexOf("<div class=\"fenliett\">"));
            PageHTTP = PageHTTP.Substring(PageHTTP.IndexOf("<table"));
            PageHTTP = PageHTTP.Substring(0, PageHTTP.IndexOf("</table>"));
            do
            {
                if (PageHTTP.IndexOf("href=") < 0)
                    break;
                string BookName, BookURL, BookInfo;
                BookInfo = PageHTTP.Substring(PageHTTP.IndexOf("<a href="));
                BookInfo = BookInfo.Substring(0, BookInfo.IndexOf("</a>"));

                BookURL = BookInfo.Substring(BookInfo.IndexOf("href=") + 6);
                BookURL = BookURL.Substring(0, BookURL.IndexOf("\""));
                BookURL = @"http://www.nanadm.com/" + BookURL;
                BookURL.Trim();

                BookName = BookInfo.Substring(BookInfo.LastIndexOf(">") + 1);

                dtBookList.Rows.Add(new object[] { BookName, BookURL });

                PageHTTP = PageHTTP.Substring(PageHTTP.IndexOf("href=") + 6);

            } while (true);

            DataTable dtTemp = new DataTable();
            dtTemp = dtBookList.Copy();
            dtBookList = new DataTable();
            dtBookList.Columns.Add("Name");
            dtBookList.Columns.Add("URL");

            for (int i = 0; i < dtTemp.Rows.Count; i++)
            {
                object[] TempObjects = dtTemp.Rows[i].ItemArray;

                if (dtBookList.Select("URL='" + Convert.ToString(TempObjects[0]) + "'").Length <= 0)
                {
                    dtBookList.Rows.Add(TempObjects);
                }
            }
            return dtBookList;
        }

        private void tsSetting_Click(object sender, EventArgs e)
        {
            dlgSetting dlgsetting = new dlgSetting();
            if (dlgsetting.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                ReadSettings();
                tsslState.Text = DownLoadDIR;
                downloadProcess1.downLoadDir = DownLoadDIR;
                downloadProcess1.zippedFiles = ZippedFiles;
                downLoadProcess2.downLoadDir = DownLoadDIR;
                downLoadProcess2.zippedFiles = ZippedFiles;
                downLoadProcess3.downLoadDir = DownLoadDIR;
                downLoadProcess3.zippedFiles = ZippedFiles;
            }
        }

        private void ReadSettings()
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            AppSettingsSection appStettings = (AppSettingsSection)config.GetSection("appSettings");
            if (appStettings.Settings["UpdateURL"] == null)
            {
                appStettings.Settings.Add("UpdateURL", "http://www.nanadm.com/dahai/888/");
                config.Save(System.Configuration.ConfigurationSaveMode.Modified);
            }
            else
            {
                UpdateURL = appStettings.Settings["UpdateURL"].Value;
            }

            if (appStettings.Settings["DownLoadDIR"] == null)
            {
                appStettings.Settings.Add("DownLoadDIR", @"c:\OverDL\");
                config.Save(System.Configuration.ConfigurationSaveMode.Modified);
            }
            else
            {
                DownLoadDIR = appStettings.Settings["DownLoadDIR"].Value;
            }

            if (appStettings.Settings["ZIPFile"] == null)
            {
                appStettings.Settings.Add("ZIPFile", @"1");
                ZippedFiles = true;
                config.Save(System.Configuration.ConfigurationSaveMode.Modified);
            }
            else
            {
                if (Convert.ToInt32(appStettings.Settings["ZIPFile"].Value) > 0)
                {
                    ZippedFiles = true;
                }
                else
                {
                    ZippedFiles = false;
                }
            }
        }

        private void tsUpdateComic_Click(object sender, EventArgs e)
        {
            tsslState.Text = "正在获取更新列表";
            Application.DoEvents();
            DataTable dtTemp = AnalysisUpdateAsync();
            for (int i = 0; i < dtTemp.Rows.Count; i++)
            {
                dtDownloadList.Rows.Add(dtTemp.Rows[i].ItemArray);
            }
            timer1.Start();
        }

        private void tsmiFullSite_Click(object sender, EventArgs e)
        {
            tsslState.Text = "正在获取漫画列表";
            Application.DoEvents();
            DataTable dtTemp = AnalysisFullSiteAsync();
            for (int i = 0; i < dtTemp.Rows.Count; i++)
            {
                dtDownloadList.Rows.Add(dtTemp.Rows[i].ItemArray);
            }
            timer1.Start();
        }

        private void textBox1_Enter(object sender, EventArgs e)
        {
            textBox1.SelectAll();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            tsslState.Text = "当前下载队列还有" + Convert.ToString(dtDownloadList.Rows.Count) + "项。";
            if (dtDownloadList.Rows.Count <= 0)
            {
                if (!downloadProcess1.IsBusy && !downLoadProcess2.IsBusy && !downLoadProcess3.IsBusy)
                {
                    btnStart.Enabled = true;
                    timer1.Stop();
                }
            }
            else
            {
                if (!downloadProcess1.IsBusy)
                {
                    string ComicURL = Convert.ToString(dtDownloadList.Rows[0].ItemArray[1]);
                    dtDownloadList.Rows.RemoveAt(0);
                    downloadProcess1.StartDownLoad(ComicURL);
                }
                if (!downLoadProcess2.IsBusy && dtDownloadList.Rows.Count > 0)
                {
                    string ComicURL = Convert.ToString(dtDownloadList.Rows[0].ItemArray[1]);
                    dtDownloadList.Rows.RemoveAt(0);
                    downLoadProcess2.StartDownLoad(ComicURL);
                }
                if (!downLoadProcess3.IsBusy && dtDownloadList.Rows.Count > 0)
                {
                    string ComicURL = Convert.ToString(dtDownloadList.Rows[0].ItemArray[1]);
                    dtDownloadList.Rows.RemoveAt(0);
                    downLoadProcess3.StartDownLoad(ComicURL);
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            textBox1.Focus();
        }
    }
}
